package com.hnu.highlynewapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hnu.highlynewapp.entity.*;
import com.hnu.highlynewapp.exception.LoginFailException;
import com.hnu.highlynewapp.service.*;
import com.hnu.highlynewapp.vo.LoginVo;
import com.hnu.highlynewapp.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.UUID;


@Service
public class LoginService {

    @Autowired
    UserService userService;
    @Autowired
    BusinessInfoService businessInfoService;
    @Autowired
    SchoolInfoService schoolInfoService;

    public UserVo login(LoginVo loginVo) throws LoginFailException {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",loginVo.getPhone())
                .eq("password",DigestUtils.md5DigestAsHex(loginVo.getPassword().getBytes()));
        UserEntity one = userService.getOne(wrapper);
        if (one == null) {
            throw new LoginFailException();
        }
        String token = UUID.randomUUID().toString().replace("-","");
        one.setToken(token);
        userService.updateById(one);

        UserVo vo = new UserVo();
        vo.setUid(one.getUserId());
        vo.setToken(token);
        vo.setType(one.getType());
        return vo;
    }

    public UserVo loginByToken(String token)  {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("token",token);
        UserEntity one = userService.getOne(wrapper);
        if (one == null) {
            return null;
        }
        String newToken = UUID.randomUUID().toString().replace("-","");
        one.setToken(newToken);
        userService.updateById(one);
        UserVo vo = new UserVo();
        vo.setUid(one.getUserId());
        vo.setToken(newToken);
        vo.setType(one.getType());

        return vo;
    }
}
